package com.apt.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import com.apt.common.AptException;
import com.apt.common.DBUtility;
import com.apt.model.ForgotPwd;
import com.apt.model.LoginDetails;

public class UserMasterDao extends BaseConnection {

	public UserMasterDao(Connection conn) {
		super(conn);

	}

	public ForgotPwd getUserDetails(String collegeId) throws AptException {
		ForgotPwd user = null;
		try {

			PreparedStatement ps = connection
					.prepareStatement("SELECT USER_ID,PASSWORD FROM USER_MASTER WHERE COLLEGE_USER_ID=?");
			ps.setString(1, collegeId);

			ResultSet rs = ps.executeQuery();
			while (rs.next()) {

				user = new ForgotPwd(rs.getString(1), rs.getString(2));

			}
			rs.close();

		} catch (SQLException sqlEx) {
			sqlEx.printStackTrace();
			throw new AptException(
					"Unable to get userId/pwd details for collegeId:"
							+ collegeId);

		} finally {
			DBUtility.cleanUp(connection);

		}

		return user;

	}

	public int updatePwd(String userId, String pwd) throws AptException {

		try {

			PreparedStatement ps = connection
					.prepareStatement("UPDATE USER_MASTER SET PASSWORD = ? WHERE USER_ID = ? ");
			ps.setString(1, pwd);
			ps.setString(2, userId);
			int update = ps.executeUpdate();
			connection.commit();
			return update;

		} catch (SQLException sqlEx) {
			sqlEx.printStackTrace();
			throw new AptException("Unable to update the password for userId:"
					+ userId);

		} finally {
			
			DBUtility.cleanUp(connection);

		}

	}

	public LoginDetails loginAndGetRoleId(String userId, String pwd)
			throws AptException {
		Integer roleid = null;		
		String name=null;

		try {
						
			PreparedStatement ps = connection
					.prepareStatement("SELECT ROLE_ID,PASSWORD,FIRST_NAME FROM USER_MASTER WHERE USER_ID=?");
			ps.setString(1, userId);

			ResultSet rs = ps.executeQuery();
			if (rs.next()) {

				String password = rs.getString(2);
				name = rs.getString(3);
				
				if (password.equals(pwd)) {
					// if user can login , only then send the role id. The caller assumes that if roleId is null, user has given invalid username/password
					
					roleid = new Integer(rs.getInt(1));

				}

			}
			rs.close();

		} catch (SQLException sqlEx) {
			sqlEx.printStackTrace();
			throw new AptException(
					"Unable to get userId/pwd details for userId:" + userId);

		} finally {
			DBUtility.cleanUp(connection);

		}
		
		return new LoginDetails(roleid,name);

	}

}
